<template>
  <div class="permission-demo-container">
    <el-card>
      <template #header>
        <span>权限控制演示</span>
      </template>

      <!-- 角色权限演示 -->
      <el-divider content-position="left">角色权限控制</el-divider>
      <div class="demo-section">
        <p>当前用户角色：{{ roles.join(', ') }}</p>
        <div class="button-group">
          <el-button v-has-role="'admin'" type="primary">
            管理员可见
          </el-button>
          <el-button v-has-role="'user'" type="success">
            普通用户可见
          </el-button>
          <el-button v-has-role="['admin', 'user']" type="info">
            管理员和用户都可见
          </el-button>
        </div>
      </div>

      <!-- 权限码控制演示 -->
      <el-divider content-position="left">权限码控制</el-divider>
      <div class="demo-section">
        <p>当前用户权限：{{ permissions.join(', ') }}</p>
        <div class="button-group">
          <el-button v-has-permission="'system:user:add'" type="primary">
            新增用户权限
          </el-button>
          <el-button v-has-permission="'system:user:edit'" type="warning">
            编辑用户权限
          </el-button>
          <el-button v-has-permission="'system:user:delete'" type="danger">
            删除用户权限
          </el-button>
        </div>
      </div>

      <!-- 数据权限演示 -->
      <el-divider content-position="left">数据权限控制</el-divider>
      <div class="demo-section">
        <p>数据权限范围：{{ dataScope }}</p>
        <mobile-table
          :data="filteredTableData"
          :current-page="1"
          :page-size="10"
          :total="filteredTableData.length"
          :show-pagination="false"
        >
          <!-- 桌面端表格 -->
          <template #desktop-table>
            <el-table :data="filteredTableData" style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="department" label="部门" />
              <el-table-column prop="creator" label="创建者" />
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button
                    v-if="canEdit(row)"
                    type="primary"
                    size="small"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-if="canDelete(row)"
                    type="danger"
                    size="small"
                  >
                    删除
                  </el-button>
                  <span v-if="!canEdit(row) && !canDelete(row)" class="no-permission">
                    无权限
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </template>

          <!-- 移动端卡片 -->
          <template #mobile-card="{ row }">
            <div class="demo-card">
              <div class="demo-header">
                <h4>{{ row.name }}</h4>
                <span class="demo-id">#{{ row.id }}</span>
              </div>
              <div class="demo-details">
                <p><strong>部门：</strong>{{ row.department }}</p>
                <p><strong>创建者：</strong>{{ row.creator }}</p>
              </div>
              <div class="demo-actions">
                <el-button
                  v-if="canEdit(row)"
                  type="primary"
                  size="small"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="canDelete(row)"
                  type="danger"
                  size="small"
                >
                  删除
                </el-button>
                <span v-if="!canEdit(row) && !canDelete(row)" class="no-permission">
                  无权限操作
                </span>
              </div>
            </div>
          </template>
        </mobile-table>
      </div>

      <!-- 动态权限检查 -->
      <el-divider content-position="left">动态权限检查</el-divider>
      <div class="demo-section">
        <div class="permission-checks">
          <div class="check-item">
            <span>是否为管理员：</span>
            <el-tag :type="isAdmin ? 'success' : 'danger'">
              {{ isAdmin ? '是' : '否' }}
            </el-tag>
          </div>
          <div class="check-item">
            <span>是否有用户管理权限：</span>
            <el-tag :type="hasUserManagePermission ? 'success' : 'danger'">
              {{ hasUserManagePermission ? '有' : '无' }}
            </el-tag>
          </div>
          <div class="check-item">
            <span>是否有系统配置权限：</span>
            <el-tag :type="hasSystemConfigPermission ? 'success' : 'danger'">
              {{ hasSystemConfigPermission ? '有' : '无' }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 权限测试按钮 -->
      <el-divider content-position="left">权限测试</el-divider>
      <div class="demo-section">
        <div class="button-group">
          <el-button @click="testPermission('admin')">
            测试管理员权限
          </el-button>
          <el-button @click="testPermission('user:add')">
            测试新增用户权限
          </el-button>
          <el-button @click="testApiPermission">
            测试API权限
          </el-button>
          <el-button @click="batchCheckPermissions">
            批量权限检查
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { usePermission } from '@/utils/permissionMiddleware'
import { filterDataByPermission, hasDataPermission, getDataScope } from '@/utils/dataPermission'
import MobileTable from '@/components/MobileTable/index.vue'

const userStore = useUserStore()
const { hasRole, hasPermission, hasApiPermission, batchCheck } = usePermission()

const roles = computed(() => userStore.roles)
const permissions = computed(() => userStore.permissions)
const userInfo = computed(() => userStore.userInfo)

// 权限检查结果
const isAdmin = computed(() => hasRole('admin'))
const hasUserManagePermission = computed(() => hasPermission('system:user'))
const hasSystemConfigPermission = computed(() => hasPermission('system:config'))

// 数据权限范围
const dataScope = computed(() => {
  const scope = getDataScope()
  const scopeNames = {
    '1': '全部数据',
    '2': '自定义数据',
    '3': '部门数据',
    '4': '部门及子部门数据',
    '5': '仅本人数据'
  }
  return scopeNames[scope] || '未知'
})

// 模拟表格数据
const tableData = ref([
  { id: 1, name: '张三', department: '技术部', creator: 'admin', userId: 1, deptId: '2' },
  { id: 2, name: '李四', department: '销售部', creator: 'user1', userId: 2, deptId: '3' },
  { id: 3, name: '王五', department: '技术部', creator: 'admin', userId: 1, deptId: '2' },
  { id: 4, name: '赵六', department: '人事部', creator: 'user2', userId: 3, deptId: '4' }
])

// 根据数据权限过滤表格数据
const filteredTableData = computed(() => {
  return filterDataByPermission(tableData.value, {
    userIdField: 'userId',
    deptIdField: 'deptId',
    createByField: 'creator'
  })
})

// 检查是否可以编辑
const canEdit = (row) => {
  return hasDataPermission(row, 'edit', {
    userIdField: 'userId',
    createByField: 'creator'
  })
}

// 检查是否可以删除
const canDelete = (row) => {
  return hasDataPermission(row, 'delete', {
    userIdField: 'userId',
    createByField: 'creator'
  })
}

// 测试权限
const testPermission = (permission) => {
  let result = false
  let message = ''

  if (permission === 'admin') {
    result = hasRole('admin')
    message = result ? '您是管理员' : '您不是管理员'
  } else {
    result = hasPermission(permission)
    message = result ? `您有 ${permission} 权限` : `您没有 ${permission} 权限`
  }

  ElMessage({
    type: result ? 'success' : 'warning',
    message
  })
}

// 测试API权限
const testApiPermission = () => {
  const result = hasApiPermission('/api/users', 'POST')
  ElMessage({
    type: result ? 'success' : 'warning',
    message: result ? '您有创建用户的API权限' : '您没有创建用户的API权限'
  })
}

// 批量权限检查
const batchCheckPermissions = () => {
  const checks = [
    { key: 'isAdmin', type: 'role', value: 'admin' },
    { key: 'canAddUser', type: 'permission', value: 'system:user:add' },
    { key: 'canEditUser', type: 'permission', value: 'system:user:edit' },
    { key: 'canDeleteUser', type: 'permission', value: 'system:user:delete' },
    { key: 'canCreateUserApi', type: 'api', value: { url: '/api/users', method: 'POST' } }
  ]

  const results = batchCheck(checks)
  
  console.log('批量权限检查结果：', results)
  
  const messages = []
  Object.entries(results).forEach(([key, value]) => {
    const names = {
      isAdmin: '管理员权限',
      canAddUser: '新增用户权限',
      canEditUser: '编辑用户权限',
      canDeleteUser: '删除用户权限',
      canCreateUserApi: '创建用户API权限'
    }
    messages.push(`${names[key]}: ${value ? '有' : '无'}`)
  })

  ElMessage({
    type: 'info',
    message: messages.join('\n'),
    duration: 5000
  })
}

onMounted(() => {
  console.log('当前用户信息：', userInfo.value)
  console.log('当前用户角色：', roles.value)
  console.log('当前用户权限：', permissions.value)
})
</script>

<style lang="scss" scoped>
.permission-demo-container {
  padding: 20px;
}

.demo-section {
  margin: 20px 0;
}

.button-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-top: 10px;
}

.permission-checks {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.check-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 移动端卡片样式 */
.demo-card {
  .demo-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    h4 {
      margin: 0;
      color: #333;
      font-size: 16px;
    }

    .demo-id {
      color: #666;
      font-size: 14px;
      background: #f5f5f5;
      padding: 2px 6px;
      border-radius: 3px;
    }
  }

  .demo-details {
    margin-bottom: 12px;

    p {
      margin: 6px 0;
      font-size: 14px;
      color: #666;

      strong {
        color: #333;
      }
    }
  }

  .demo-actions {
    display: flex;
    gap: 8px;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
  }
}

.no-permission {
  color: #999;
  font-size: 12px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .permission-demo-container {
    padding: 10px;
  }

  .button-group {
    flex-direction: column;
  }

  .button-group .el-button {
    width: 100%;
  }

  .demo-section {
    margin: 15px 0;
  }

  .permission-checks {
    gap: 8px;
  }

  .check-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
}
</style>
